package net.dntuan.training.mvc.controller;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dntuan.training.mvc.domain.City;
import net.dntuan.training.mvc.manager.CityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/return-type")
public class ReturnTypeController {

    @Autowired
    private CityManager cityManager;

    @RequestMapping(value = "/model-and-view")
    public ModelAndView getModelView(HttpServletRequest request) {
        List<String> headers = new ArrayList<String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerKey = headerNames.nextElement();
            headers.add(request.getHeader(headerKey));
        }
        ModelAndView modelView = new ModelAndView("model-and-view", "headers", headers);
        return modelView;
    }

    @RequestMapping(value = "/city-object-json", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public City getCityAsJson(HttpServletResponse response, @RequestParam(required = true, value = "cityId") Long id) {
        return cityManager.findOne(id);
    }

    @RequestMapping(value = "/cities-json", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<City> getCityAsJson(@RequestParam(required = true, value = "cityName") String cityName) {
        return cityManager.search(cityName, null, null, null);
    }

    @RequestMapping(value = "/city-object-xml", produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public City getCityAsXml(@RequestParam(required = true, value = "cityId") Long id) {
        return cityManager.findOne(id);
    }
}
